--
-- @Author:      feilong
-- @DateTime:    2019-12-11 23:05:48
-- @Description: 消息的处理
local skynet = require "skynet"
local mysql = require "skynet.db.mysql"
local skynet_queue = require("skynet.queue")

local table_remove = table.remove
local table_insert = table.insert


local MessageHandler = class("MessageHandler")

---------------------------------------------------------
-- Private
---------------------------------------------------------
function MessageHandler:ctor(message_dispatch)
	self.message_dispatch = message_dispatch
	self.skynet_queue_fun = {}	
	self.host = skynet.getenv("mysql_host")
	self.port = skynet.getenv("mysql_port")
	self.db = skynet.getenv("mysql_db")
	self.user = skynet.getenv("mysql_user")
	self.password = skynet.getenv("mysql_pwd")

	self.db_info = {
		host = self.host,
		port = self.port,
		database = self.db,
		user = self.user,
		password = self.password,
		-- max_packet_size = 1024 * 1024,
	}
	debug_log("__mysql_db_info____", self.db_info)
	self.connections = {} --连接池
	self.allocated_connection_num = 0
	self.max_connection_num = 100 

	self:register()
end

--注册本服务里的消息
function MessageHandler:register()
	self.message_dispatch:registerSelf("start", handler(self,self.start))
	self.message_dispatch:registerSelf("mysql_cmd", handler(self,self.mysqlCommand))
	self.message_dispatch:registerSelf("normal_cmd", handler(self,self.normalCommand))
	self.message_dispatch:registerSelf("sync_cmd", handler(self,self.syncCommand))
end

--从连接池里取一个服务
function MessageHandler:getConnect()
    local connections = self.connections
    if #connections > 0 then
        return table_remove(connections)
    end
    while self.allocated_connection_num >= self.max_connection_num do
        --超上限了，唯有空转等了
        error_log('there is no connection for reusing, waiting for one reused connection')
        skynet.sleep(5)
        if #connections > 0 then
            return table_remove(connections)
        end
    end

    local ok,ret = xpcall(mysql.connect, debug.traceback, self.db_info)
    while not ok do
        error_log('failed to connect mysql',ret)
        skynet.sleep(100) --one second
        ok,ret = xpcall(mysql.connect, debug.traceback, self.db_info)
    end

    self.allocated_connection_num = self.allocated_connection_num + 1
    return ret
end


---------------------------------------------------------
-- CMD
---------------------------------------------------------

function MessageHandler:start(args)
	return true
end

function MessageHandler:normalCommand(...)
	-- body	
	local conn = self:getConnect()
	local func = conn["query"]
    local ok, ret = xpcall(func, debug.traceback, conn, ...)
    while not ok do
        error_log("___发送消息给mysql错误___", ret)
        skynet.sleep(100)
        print('mysql now retry....')
        ok, ret = xpcall(func, debug.traceback, conn, ...)
    end
    --把连接放回池中
	table_insert(self.connections, conn)
    if not ok then
		error_log(ret) 
	end

	return ret
end

--mysql命令处理
function MessageHandler:mysqlCommand(sync_id, ...)
	if sync_id then
		return self:syncCommand(sync_id, ...)
	end
	return self:normalCommand(...)
end

--根据sync_id同步处理
function MessageHandler:syncCommand(sync_id, ...)
	if not sync_id then
		error_log("___发送消息给redis错误___assigin_id is not__")
		return 
	end
	--按指定id同步执行
	local fun = self.skynet_queue_fun[sync_id]
	if not fun then 
		fun = skynet_queue()
		self.skynet_queue_fun[sync_id] = fun
	end
	local function call_mysql(...)
		return self:normalCommand(...)
	end
	return fun(call_mysql, ...)
end


return MessageHandler

